package com.penghaonan.appframework.utils

import android.content.Context
import android.content.SharedPreferences
import androidx.core.content.edit
import com.penghaonan.appframework.AppDelegate.getApp
import com.tencent.mmkv.MMKV

object PrefUtils {
    val default: SharedPreferences by lazy { getPref(getApp().packageName) }

    @JvmStatic
    fun getPref(pref: String?): SharedPreferences {
        val mmkv = try {
            MMKV.mmkvWithID(pref)
        } catch (ignore: Exception) {
            MMKV.initialize(getApp())
            MMKV.mmkvWithID(pref)
        }
        val migrateKey = "migrate_from_sp_2_mmkv"
        if (!mmkv.getBoolean(migrateKey, false)) {
            val sp = getApp().getSharedPreferences(pref, Context.MODE_PRIVATE)
            mmkv.importFromSharedPreferences(sp)
            mmkv.putBoolean(migrateKey, true)
        }
        return mmkv
    }

    @JvmStatic
    fun put(key: String?, value: Boolean) {
        default.edit(commit = true) { putBoolean(key, value) }
    }

    @JvmStatic
    fun containsKey(key: String?): Boolean {
        return default.contains(key)
    }

    @JvmStatic
    fun getBoolean(key: String?): Boolean {
        return getBoolean(key, false)
    }

    @JvmStatic
    fun getBoolean(key: String?, def: Boolean): Boolean {
        return default.getBoolean(key, def)
    }

    @JvmStatic
    fun put(key: String?, value: String?) {
        default.edit(commit = true) { putString(key, value) }
    }

    @JvmStatic
    fun getString(key: String?, def: String?): String? {
        return default.getString(key, def)
    }

    @JvmStatic
    fun put(key: String?, value: Long) {
        default.edit(commit = true) { putLong(key, value) }
    }

    @JvmStatic
    fun getLong(key: String?, def: Long): Long {
        return default.getLong(key, def)
    }

    @JvmStatic
    fun put(key: String?, value: Int) {
        default.edit(commit = true) { putInt(key, value) }
    }

    @JvmStatic
    fun getInt(key: String?, def: Int): Int {
        return default.getInt(key, def)
    }

    @JvmStatic
    fun put(key: String?, items: MutableSet<String?>?) {
        default.edit(commit = true) { putStringSet(key, items) }
    }

    @JvmStatic
    fun getStringSet(key: String?, def: MutableSet<String?>?): MutableSet<String?>? {
        return default.getStringSet(key, def)
    }

    @JvmStatic
    fun put(key: String?, value: Float) {
        default.edit(commit = true) { putFloat(key, value) }
    }

    @JvmStatic
    fun getFloat(key: String?, def: Float): Float {
        return default.getFloat(key, def)
    }
}
